/**
 * @author: YUPPIE
 * @date: 2025-04-18
 * @description: router 路由管理模块
 * @version: 1.0
 *
 */
import { constantRoutes } from "@/router/index";
import { RouteRecordRaw } from "vue-router";
import { getRoutesRequest } from "@/api/system/menu";
import router from "@/router";
const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");
export const usePermissionStore = defineStore("permission", {
  state: () => ({
    routes: [] as RouteRecordRaw[], //所有路由，包括默认路由与动态路由
    menuRoutes: [], //菜单路由，不包括默认路由
    routesLoaded: false, //路由是否加载完成
  }),
  getters: {},
  actions: {
    _parseDynamicRoutes(rawRoutes: any) {
      const parsedRoutes = [] as any;
      rawRoutes.forEach((route: any) => {
        const component = route.component;
        if (component) {
          route.component =
            component?.toString() === "Layout"
              ? Layout
              : modules[`../../views/${component}.vue`] ||
                modules["../../views/error-page/404.vue"];
        }
        if (route.children && route.children.length > 0) {
          route.children = this._parseDynamicRoutes(route.children);
        }
        parsedRoutes.push(route);
      });
      return parsedRoutes;
    },
    // 获取后台动态路由数据，解析并注册到全局路由
    getRoutesRequest(params?: any) {
      return new Promise((resolve, reject) => {
        getRoutesRequest(params)
          .then((res: any) => {
            if (res.code == 200) {
              const dynamicRoutes = this._parseDynamicRoutes(res.data);
              this.routes = [...constantRoutes, ...dynamicRoutes];
              dynamicRoutes.forEach((item: any) => {
                router.addRoute(item);
              });
              params && params.callback && params.callback(dynamicRoutes);
            }
            this.routesLoaded = true;
            resolve(res.data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    // 根据父菜单路径设置混合模式左侧菜单
    setMenuRoutes() {},
    // 重置路由
    resetRouter() {
      //  从 router 实例中移除动态路由
      this.routes.forEach((route) => {
        const { name } = route;
        if (name && !constantRoutes.find((item) => item.name == name)) {
          router.removeRoute(name);
        }
      });
      this.routes = [];
      this.menuRoutes = [];
      this.routesLoaded = false;
    },
  },
});
